/* eslint-disable react/prop-types */
/* eslint-disable eqeqeq */
/* eslint-disable camelcase */
import { Tabs, message, Spin } from 'antd';
import React, { useState, useEffect } from 'react';
import { withRouter } from 'react-router';
import _ from 'lodash';
const { TabPane } = Tabs;
import { getNodeList, nodeLogs, nodeInfo } from '@api/nodes';
import { connect } from 'react-redux';
import './index.less';
const tabs = [
  {
    name: '系统负载',
    key: '1',
    components: import('./components/system-load'),
    data: []
  },
  {
    name: '业务负载',
    key: '2',
    components: import('./components/business-load'),
    data: []
  }
];
// eslint-disable-next-line react/prop-types
let timer = null;
const EquipmentLoad = ({ location, hasCluster, cert }) => {
  const [defaultActiveKey, setDefaultActiveKey] = useState('1');
  const [tabPanes, setTabPanes] = useState(tabs);
  const [selectList, setSelectList] = useState([]);
  const [outSpinning, setOutSpinning] = useState(false);
  // eslint-disable-next-line no-unused-vars
  const [innerSpinning, setInnerSpinning] = useState(false);
  const [selectVal, setSelectVal] = useState();
  const [detail, setDetail] = useState();
  // const [timer, setTimer] = useState(null);
  const getDetail = list => {
    let data = list.sort((a, b) => {
      const dateA = new Date(a.created);
      const dateB = new Date(b.created);
      return dateA - dateB;
    });
    let rebuildData = {
      created_at: [],
      cpu_percent_list: [],
      cpu_percent: '',
      mem_percent: '',
      disk_data_percent: '',
      disk_data_percent_list: [],
      net_packets_sent: '',
      net_packets_sent_list: [],
      mem_percent_list: [],
      net_packets_recv: '',
      net_packets_recv_list: []
    };
    data.map((r, i) => {
      rebuildData.cpu_percent_list.push(r.cpu),
        rebuildData.mem_percent_list.push(r.memory),
        rebuildData.disk_data_percent_list.push(r.disk),
        rebuildData.created_at.push(r.created);
      rebuildData.net_packets_recv_list.push(r.netRecive);
      rebuildData.net_packets_sent_list.push(r.netSend);
      if (i === data.length - 1) {
        rebuildData.cpu_percent = r.cpu;
        rebuildData.mem_percent = r.memory;
        rebuildData.disk_data_percent = r.disk;
        rebuildData.net_packets_recv = r.netRecive;
        rebuildData.net_packets_sent = r.netSend;
      }
    });
    setDetail(rebuildData);
  };
  const getNodeLogs = ip => {
    if (!ip) {
      return;
    }
    setInnerSpinning(true);
    nodeLogs(ip)
      .then(res => {
        let data = _.get(res, 'data.data.nodeLogList', []);
        getDetail(data);
      })
      .catch(() => {
        message.error('获取列表失败');
      })
      .finally(() => {
        setInnerSpinning(false);
      });
  };

  const getloop = ip => {
    timer = setInterval(() => {
      getNodeLogs(ip);
    }, 4000);
  };

  const setDataListInfo = list => {
    const cloneList = [...list];
    list.forEach(r => {
      nodeInfo(r?.node_ip).then(data => {
        const result = data?.data?.data;
        let index = list.findIndex(i => i.node_ip === result.node_ip);
        cloneList[index] = { ...cloneList[index], ...result };
        setSelectList(cloneList);
      });
    });
  };

  // 获取节点列表
  const NodeList = () => {
    getNodeList()
      .then(res => {
        let list = _.get(res, 'data.data', []);
        // 如果是单机取证书里的ip
        if (!hasCluster) {
          list = [{ node_ip: cert?.local_node_ip, node_role: 'single' }];
        }
        // 如果是集群，集群列表为空，说明是集群组装前，取证书的信息
        if (hasCluster && list.length === 0) {
          list = [{ node_ip: cert?.local_node_ip, node_role: 'master' }];
        }
        setSelectList(list);
        setDataListInfo(list);
        let master = list.find(r => r.node_role === 'master' || r.node_role === 'single');
        let masterIp = master?.node_ip;
        let {
          ip = masterIp
          // name=master?.node_name
        } = _.get(location, 'state', {});
        setSelectVal(ip);
        getNodeLogs(ip);
        getloop(ip);
      })
      .catch(() => {
        message.error('获取列表失败');
      });
  };

  useEffect(() => {
    const loadTabs = async () => {
      const updatedTabPanes = await Promise.all(
        tabs.map(async r => {
          const { name, key, components, selectList } = r;
          const Component = components ? (await components).default : null;
          return { name, key, Component, selectList };
        })
      );
      setOutSpinning(false);
      setTabPanes(updatedTabPanes);
    };

    loadTabs();
  }, [tabs]);

  useEffect(() => {
    if (location.state) {
      const { type } = location.state;
      setDefaultActiveKey(type);
    }
  }, [location]);

  useEffect(() => {
    NodeList();
    return () => {
      window.clearInterval(timer);
    };
  }, []);

  const tabsCallback = key => {
    setDefaultActiveKey(key);
    let master = selectList.find(r => r.node_role === 'master' || r.node_role === 'single');
    setSelectVal(master?.node_ip);
    getNodeLogs(master?.node_ip);
    window.clearInterval(timer);
    getloop(master?.node_ip);
  };

  const changeSelect = key => {
    setSelectVal(selectList.find(r => r.node_ip == key)?.node_ip);
    getNodeLogs(key);
    window.clearInterval(timer);
    getloop(key);
    window.clearInterval(timer);
  };

  return (
    <Spin tip="加载中" spinning={outSpinning} className="spin-wrapper h100">
      {!outSpinning && (
        <Tabs
          activeKey={defaultActiveKey}
          onChange={tabsCallback}
          style={{ backgroundColor: '#ffffff' }}
          className="h100"
        >
          {tabPanes.map(r => {
            let { name, key, Component } = r;
            return (
              <TabPane tab={name} key={key}>
                <Spin tip="加载中" spinning={false} className="spin-wrapper h100">
                  {Component && (
                    <Component
                      title={name}
                      selectList={selectList}
                      changeSelect={changeSelect}
                      selectVal={selectVal}
                      detail={detail}
                    />
                  )}
                </Spin>
              </TabPane>
            );
          })}
        </Tabs>
      )}
    </Spin>
  );
};

const mapStateToProps = state => {
  return {
    hasCluster: _.includes(state?.auth?.cert?.modules, 'distribute'),
    cert: _.get(state, 'auth.cert', {})
  };
};

export default withRouter(connect(mapStateToProps)(EquipmentLoad));
